package hkr.se1.cyvasse;

import Game.Game;
import Game.Tile;
import android.content.Context;
import android.view.Gravity;
import android.widget.LinearLayout;

public class BoardView extends LinearLayout {

	private Game game;
	private TileView[][] boardView;

	public BoardView(Context context, Game game) {
		super(context);
		this.game = game;
		init(context);

	}

	public void init(Context context) {
		setOrientation(LinearLayout.VERTICAL);
		boardView = new TileView[8][8];
		int counter = 0;
		for (int row = 0; row < 8; row++) {
			LinearLayout linearLayout = new LinearLayout(context);
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			
			for (int col = 0; col < 8; col++) {
				TileView tile = new TileView(context, game);
				tile.setId(counter);
				tile.setPadding(1, 1, 1, 1);
				boardView[row][col] = tile;
				linearLayout.addView(tile, 50, 50);
				counter++;
			}
			addView(linearLayout);
		}

		draw();

		LayoutParams params = new LayoutParams(0, 0);
		params.gravity = Gravity.CENTER;
		params.width = 400;
		params.height = 400;
		setLayoutParams(params);
	}

	public void setShaderImage(int x, int y, int type) {
		TileView tile = boardView[y][x];
		tile.setShader(type);
	}

	public void setupScreen(boolean isBlack, boolean isCovered) {

		int startRow;
		int endRow;
		int clearStart;
		int clearEnd;

		if (isCovered) {
			if (!isBlack) {
				startRow = 4;
				endRow = 7;
				clearStart = 0;
				clearEnd = 3;
			} else {
				startRow = 0;
				endRow = 3;
				clearStart = 4;
				clearEnd = 7;
			}
			for (int r = startRow; r <= endRow; r++) {
				for (int c = 0; c < 8; c++) {
					setCoverVisibility(c, r, true);
				}
			}
			for (int r = clearStart; r <= clearEnd; r++) {
				for (int c = 0; c < 8; c++) {
					setCoverVisibility(c, r, false);
				}
			}
		} else {
			for (int r = 0; r < 8; r++) {
				for (int c = 0; c < 8; c++) {
					setCoverVisibility(c, r, false);
				}
			}
		}
	}

	private void setCoverVisibility(int x, int y, boolean visibility) {
		TileView tile = boardView[y][x];
		tile.setCoverVisibility(visibility);
	}

	public void draw() {
		Tile[][] board = game.getBoard();
		for (int row = 0; row < 8; row++) {
			for (int col = 0; col < 8; col++) {
				TileView tile = boardView[row][col];
				if (board[row][col].getPiece() != null) {
					tile.setPieceImage(board[row][col].getPiece().getImageId());
				}
				tile.setTileImage(board[row][col].getImageId());
			}
		}
	}

}
